// src/pages/admin/user/OperationLogs.jsx
import React, { useState, useEffect } from 'react';
import { Table, Button, Card, Spin, Tag, Input, Select } from 'antd';
import { HistoryOutlined, SearchOutlined } from '@ant-design/icons';
import axios from 'axios';
import { getAuthToken } from '@/router';

const { Option } = Select;

// 静态操作类型列表（替代API获取）
const STATIC_OPERATION_TYPES = [
  'USER_BAN',
  'TORRENT_APPROVE',
  'TORRENT_REJECT',
  'USER_UNBAN',
  'USER_UPDATE',
  'TORRENT_DELETE'
];

// Mock data for when API fails
const mockOperationLogs = {
  data: {
    records: [
      {
        id: 1,
        operationType: 'USER_BAN',
        operationContent: '封禁用户违规用户1',
        operatorName: '管理员1',
        targetType: 'USER',
        targetId: 101,
        createdAt: new Date().toISOString(),
        ipAddress: '192.168.1.1'
      },
      {
        id: 2,
        operationType: 'TORRENT_APPROVE',
        operationContent: '审核通过种子123',
        operatorName: '管理员2',
        targetType: 'TORRENT',
        targetId: 456,
        createdAt: new Date(Date.now() - 3600000).toISOString(), // 1 hour ago
        ipAddress: '192.168.1.2'
      }
    ],
    current: 1,
    size: 10,
    total: 2
  }
};

const OperationLogs = () => {
  const [loading, setLoading] = useState(true);
  const [logs, setLogs] = useState([]);
  const [filters, setFilters] = useState({
    operationType: '',
    keyword: ''
  });
  const [pagination, setPagination] = useState({ current: 1, pageSize: 10, total: 0 });

  const fetchData = async (page = 1, pageSize = 10) => {
    try {
      setLoading(true);
      const params = {
        page,
        size: pageSize,
        operationType: filters.operationType,
        keyword: filters.keyword
      };

      const response = await axios.get('http://localhost:8080/api/admin/user/operation-logs', {
        params,
        headers: { Authorization: getAuthToken() }
      });

      if (response.data.code === 200) {
        setLogs(response.data.data.records);
        setPagination({
          current: response.data.data.current,
          pageSize: response.data.data.size,
          total: response.data.data.total
        });
      } else {
        message.error(response.data.message || '获取数据失败');
      }
    } catch (error) {
      console.error('获取操作日志失败，使用模拟数据:', error);
      setLogs(mockOperationLogs.data.records);
      setPagination({
        current: mockOperationLogs.data.current,
        pageSize: mockOperationLogs.data.size,
        total: mockOperationLogs.data.total
      });
      message.warn('后端连接失败，使用模拟数据');
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchData();
  }, []);

  const handleTableChange = (pagination) => {
    fetchData(pagination.current, pagination.pageSize);
  };

  const handleFilterChange = (key, value) => {
    setFilters(prev => ({ ...prev, [key]: value }));
  };

  const handleSearch = () => {
    fetchData(1, pagination.pageSize);
  };

  const columns = [
    {
      title: '操作类型',
      dataIndex: 'operationType',
      key: 'operationType',
      render: type => <Tag color="blue">{type}</Tag>
    },
    {
      title: '操作内容',
      dataIndex: 'operationContent',
      key: 'operationContent'
    },
    {
      title: '操作人',
      dataIndex: 'operatorName',
      key: 'operatorName'
    },
    {
      title: '目标',
      dataIndex: 'targetType',
      key: 'targetType',
      render: (_, record) => `${record.targetType} #${record.targetId}`
    },
    {
      title: '操作时间',
      dataIndex: 'createdAt',
      key: 'createdAt',
      render: date => new Date(date).toLocaleString()
    },
    {
      title: 'IP地址',
      dataIndex: 'ipAddress',
      key: 'ipAddress'
    }
  ];

  return (
      <Card
          title="操作日志"
          bordered={false}
          extra={
            <div style={{ display: 'flex', gap: 10 }}>
              <Select
                  placeholder="操作类型"
                  style={{ width: 150 }}
                  onChange={value => handleFilterChange('operationType', value)}
                  allowClear
              >
                {STATIC_OPERATION_TYPES.map(type => (
                    <Option key={type} value={type}>{type}</Option>
                ))}
              </Select>
              <Input
                  placeholder="搜索内容"
                  value={filters.keyword}
                  onChange={e => handleFilterChange('keyword', e.target.value)}
                  style={{ width: 200 }}
              />
              <Button
                  type="primary"
                  icon={<SearchOutlined />}
                  onClick={handleSearch}
              >
                搜索
              </Button>
            </div>
          }
      >
        <Spin spinning={loading}>
          <Table
              columns={columns}
              dataSource={logs}
              rowKey="id"
              pagination={pagination}
              onChange={handleTableChange}
          />
        </Spin>
      </Card>
  );
};

export default OperationLogs;